import axios from 'axios'
import { Message } from 'element-ui'
import router from '../router/index'

// create an axios instance
const service = axios.create({
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

service.interceptors.request.use(
  config => {
    // const access_token = sessionStorage.getItem('access_token')
    config.params = Object.assign(
      config.params || {},
      {
        access_token: sessionStorage.getItem('access_token')
      }
    )
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    // if (res.code !== 200) {
    //   Message({
    //     message: res.text,
    //     type: 'error',
    //     duration: 2 * 1000
    //   })
    // }
    return res
  },
  error => {
    console.log(error.response, 'err') // for debug
    if (+error.response.status === 401) {
      Message({
        message: '登录失效，请重新登录',
        type: 'warning',
        duration: 2 * 1000
      })
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    }
    if (+error.response.status !== 200) {
      Message({
        message: error.response.data.text,
        type: 'warning',
        duration: 2 * 1000
      })
    }

    return Promise.reject(error)
  }
)

export default service
